package com.orhon.smartcampus.modules.material.fetcher;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.orhon.smartcampus.auth.JwtUtils;
import com.orhon.smartcampus.modules.user.dao.TokenService;
import com.orhon.smartcampus.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.entity.Schools;
import com.orhon.smartcampus.modules.base.gqlModel.GQLPageParam;
import com.orhon.smartcampus.modules.base.gqlModel.GQLSchool;
import com.orhon.smartcampus.modules.base.mm.EnvArgsMapper;
import com.orhon.smartcampus.modules.base.mm.SchoolMapper;
import com.orhon.smartcampus.modules.material.dao.CampusDao;
import com.orhon.smartcampus.modules.material.entity.Campus;
import com.orhon.smartcampus.modules.material.gqlModel.GQLCampus;
import com.orhon.smartcampus.modules.material.mm.CampusMapper;
import com.orhon.smartcampus.utils.ObjectToMap;
import com.orhon.smartcampus.utils.Util;

import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;

@Component
public class CampusListFetcher implements DataFetcher  {

	@Autowired
	CampusDao campusDao;

	@Autowired
	TokenService tokenService;

	@Override
	public Object get(DataFetchingEnvironment env) throws Exception {

		String token = tokenService.getSystemToken();
		if(token==null) {
			return  R.NoLogin();
		}
		Long schoolId = JwtUtils.getSchoolId(token);

		List<GQLCampus> GQLCampus = new ArrayList<>();
		GQLPageParam page = EnvArgsMapper.MAPPER.fromArgs(env);

		String hql = "from Campus  where deleted_at = null and school_id = " + schoolId;
		if(env.containsArgument("condition")) {
            HashMap<String,Object> map = ObjectToMap.to(env.getArgument("condition"));
            if(map.get("school_id")!=null) {
                hql += "and school_id " + Util.decide(map.get("school_id"));
            }
			if(map.get("id")!=null) {
				hql += "and id " + Util.decide(map.get("id"));
			}
		}	
		List<Campus> list = campusDao.find(hql,null,page.getPage(),page.getLimit());

		for (Campus item : list) {
			GQLSchool GgqlSchool = null;
			if (env.getSelectionSet().contains("data/school")){
				Schools schools = item.getBaseSchoolsBySchoolId();
				GgqlSchool = SchoolMapper.MAPPER.toSchool(schools);
			}
			GQLCampus campus = CampusMapper.MAPPER.toCampus(item);
			campus.setSchool(GgqlSchool);
			GQLCampus.add(campus);
		}
		Long total = 0L;
		if (env.getSelectionSet().contains("total")){
			total = campusDao.getTotalCount(hql);
		}
		return Result.ok().put("data", GQLCampus).put("total", total);
	}
}
